<template>
  <div class="addEditExam exercises-box">
    <div class="coutentBox">
      <div class="top-box">
        <div class="title">
          <div class="flex">
            考生库基本信息
          <div class="showStyle" v-if="showFlag">
            考生库名称: {{ exercisesForm.studentPool }}
          </div>
          </div>
          
          <div style="padding-right: 10px;"><el-button type="text" @click="showFlag = !showFlag">{{ showFlag ? '展开' : '收起'}}</el-button></div>
        </div> 
        <el-form
          v-if='!showFlag'
          :model="exercisesForm"
          :rules="exercisesFormRules"
          ref="exercisesForm"
          label-width="100px"
          style="padding:10px 10px 0 0"
          label-position="right"
        >
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="考生库名称" prop="studentPool">
                <el-input
                  v-model="exercisesForm.studentPool"
                  style="width: 100%"
                  placeholder="考生库名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="top-box bottom-box">
        <p class="title">考生列表</p>
        <div class="tab-inner">
          <div class="searchBox" v-if="addOrUpdateFlag == 'edit'">searchBox</div>
          <div class="aggridBox">
            <el-table
            :data="tableData"
            border
            style="width: 100%" size='mini'>
            <el-table-column
              prop="date"
              label="日期"
              width="180">
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="180">
            </el-table-column>
            <el-table-column
              prop="address"
              label="地址">
            </el-table-column>
          </el-table>
        
          </div>
          <div class="pageBox">
            <div>
              选择 <strong style="color: #00b99e;">{{ dataSelect.length }}</strong> 数据
            </div>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="page.pageSizes"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div class="buttonBottomBox">
      <el-button @click="back" size="small">
        <span class="icon iconfont icon-fanhui"></span>
        返回
      </el-button>
      <el-button type="primary" @click="back" size="small">
        <span class="icon iconfont icon-zidingyitianjia"></span>
        自定义添加
      </el-button>
      <el-button type="warning" size="small">
        <a
          href="../../../static/file/student.csv"
          download="学生模板.csv"
          style="color: #fff"
          ><span
            class="icon iconfont icon-xiazaimoban"
            style="margin-right: 4px"
          ></span
          >下载模板</a
        >
      </el-button>
      <el-button type="danger" @click="exportHandle" size="small">
        <span class="icon iconfont icon-xiazaimoban"></span>
        导入模板
      </el-button>
    </div>
    <!-- 导入数据 start-->
    <el-dialog
      title="导入学生"
      top="20px"
      :visible.sync="exportVisible"
      width="90%"
    >
      <div class="importBox">
        <div class="tab-box">
          <div class="flex top-box">
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <div
                style="
                  font-size: 16px;
                  font-weight: 600;
                  color: #333;
                  padding-left: 10px;
                "
              >
                导入学生：
              </div>
              <input
                class="inputStyle"
                type="file"
                @change="handleFileUpload"
              />
            </div>
            <el-button
              type="primary"
              size="small"
              :disabled="excelData.length == 0"
              @click="uploadData"
              >确认</el-button
            >
          </div>
          <div v-if="excelDataBak || col.length > 0">
            <el-table
              :data="excelData"
              border
              style="width: 100%"
              size="mini"
              :span-method="objectSpanMethod"
              :header-cell-style="{
                textAlign: 'center',
                backgroundColor: '#F5F7FA',
              }"
            >
              <el-table-column
                v-for="(item, index) in col"
                :key="index"
                :prop="item.headValue"
                :label="item.headName"
                minWidth="180"
              >
                <template slot-scope="scope">
                  {{ scope.row[item.headValue] }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="delItem(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 导入数据 end-->
  </div>
</template>
<script>
import * as XLSX from 'xlsx'
export default {
  components: {},

  props: ['addOrUpdateFlag'],
  data () {
    return {
      tableData: [],
      exercisesForm: {
        studentPool: ''
      },
      exercisesFormRules: {
        studentPool: [
          { required: true, message: '考生库不能为空', trigger: 'change' }
        ]
      },
      saveLoading: false,
      scoreSetOptions: [
        {
          label: 1,
          value: '1'
        },
        {
          label: 0.5,
          value: '0.5'
        },
        {
          label: 0.1,
          value: '0.1'
        }
      ],
      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      dataSelect: [],
      activeName: 'scoreCard',
      // new upload
      exercisesIdBak: '',
      exportVisible: false,
      excelDataBak: null,
      colFields: [],
      excelData: [],
      col: [],
      pageIndex: 1,
      pageSize: 100000,
      showFlag: false
    }
  },
  methods: {
    back () {
      this.$emit('back')
    },
    // 导入模板
    exportHandle () {
      if (!this.exercisesForm.studentPool) {
        this.$message.warning('学生库名称不能为空')
        return
      }
      this.exportVisible = true
    },
    // 确认导入
    uploadData () {
      console.log(this.excelData)
    },
    save (params) {
      this.$http({
        url: '/exam/selfinspectioncard/saveList',
        method: 'post',
        data: params
      }).then(({ data }) => {
        console.log(data)
        this.$message.success('保存成功～')
      })
    },
    handleFileUpload (event) {
      const file = event.target.files[0]
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        this.excelDataBak = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        // console.log("this.excelDataBak", this.excelDataBak);
        this.col = []
        this.colFields = []
        this.excelData = []

        for (let q = 0; q < this.excelDataBak.length; q++) {
          if (this.excelDataBak[q][0] === undefined) {
            this.excelDataBak[q][0] = this.excelDataBak[q - 1][0]
          }
        }
        this.excelDataBak[0].map((item, index) => {
          this.col.push({
            headName: item,
            headValue: `head${index}`
          })
          this.colFields.push(`head${index}`)
        })
        for (let i = 1; i < this.excelDataBak.length; i++) {
          let obj = {}
          for (let k = 0; k < this.excelDataBak[i].length; k++) {
            obj[`head${k}`] = this.excelDataBak[i][k]
          }
          this.excelData.push(obj)
        }
      }
      reader.readAsArrayBuffer(file)
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        // 获取当前单元格的值
        const currentValue = row[column.property]
        // 获取上一行相同列的值
        const preRow = this.excelData[rowIndex - 1]
        const preValue = preRow ? preRow[column.property] : null
        // 如果当前值和上一行的值相同，则将当前单元格隐藏
        if (currentValue === preValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          // 否则计算当前单元格应该跨越多少行
          let rowspan = 1
          for (let i = rowIndex + 1; i < this.excelData.length; i++) {
            const nextRow = this.excelData[i]
            const nextValue = nextRow[column.property]
            if (nextValue === currentValue) {
              rowspan++
            } else {
              break
            }
          }
          return { rowspan, colspan: 1 }
        }
      }
    },
    handleSizeChange () {},
    handleCurrentChange () {},
    delItem (val) {
      let arr = JSON.parse(JSON.stringify(this.excelData))
      this.excelData = arr.filter(
        (item) => JSON.stringify(item) !== JSON.stringify(val)
      )
    }
  }
}
</script>
<style lang="scss">
.addEditExam {
  height: calc(100vh - 115px);
  width: 100%;
  flex-direction: column;
  overflow: auto;
  .title{
      margin-bottom: 0 !important;
    }
  .coutentBox {
    height: 100%;
    margin: 0 !important;
    padding: 10px;
    padding-top: 54px;
    display: flex;
    flex-direction: column;
    
    .showStyle{
      padding-left: 10px;
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 14px;
    }
    .bottom-box {
      flex: 1;
      overflow: auto;
      margin-bottom: 0;
    }
  }
  .buttonBottomBox {
    height: 50px;
    position: absolute;
    padding: 0 20px;
    top: 0;
    width: 100%;
    background: #ffffff90;
    backdrop-filter: blur(5px);
    left: 0;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .tab-inner {
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: calc(100% - 42px);
    .aggridBox {
      flex: 1;
      background: powderblue;
    }
  }
}
.importBox {
  height: calc(100vh - 160px);
}
</style>
